<template>
  <el-drawer
    :title="title"
    v-model="drawerVisible"
    size="800px"
    :before-close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="120px"
    >

      <!-- 添加间距 -->
      <div style="margin-bottom: 20px;"></div>
      
      <el-tabs v-model="activeTab" type="card" @tab-change="handleTabChange">
        <el-tab-pane label="基础信息" name="basic">
          <el-row>
            <el-col :span="24">
              <el-form-item label="活动名称" prop="campaignName">
                <el-input v-model="form.campaignName" placeholder="请输入活动名称" />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row>
            <el-col :span="24">
              <el-form-item label="活动描述" prop="description">
                <el-input v-model="form.description" type="textarea" placeholder="请输入活动描述" />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row>
            <el-col :span="12">
              <el-form-item label="开始时间" prop="startTime">
                <el-date-picker
                  v-model="form.startTime"
                  type="datetime"
                  placeholder="请选择开始时间"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="结束时间" prop="endTime">
                <el-date-picker
                  v-model="form.endTime"
                  type="datetime"
                  placeholder="请选择结束时间"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-tab-pane>
        
        <el-tab-pane label="客户选择" name="customer" :disabled="!isTabEnabled('customer')">
          <customer-select ref="customerSelectRef" v-model="form.customerGroup" />
        </el-tab-pane>
        
        <el-tab-pane label="营销方式" name="method" :disabled="!isTabEnabled('method')">
          <marketing-method v-model="form.marketingMethods" />
        </el-tab-pane>
        
        <el-tab-pane label="执行设置" name="execution" :disabled="!isTabEnabled('execution')">
          <execution-setting 
            :trigger-type="form.triggerType"
            :scheduled-time="form.scheduledTime"
            :task-type="form.taskType"
            :recurring-pattern="form.recurringPattern"
            @update:triggerType="val => form.triggerType = val"
            @update:scheduledTime="val => form.scheduledTime = val"
            @update:taskType="val => form.taskType = val"
            @update:recurringPattern="val => form.recurringPattern = val"
          />
        </el-tab-pane>
      </el-tabs>
    </el-form>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button v-if="activeTab !== 'basic'" @click="prevStep">上一步</el-button>
        <el-button v-if="activeTab !== 'execution'" type="primary" @click="nextStep">下一步</el-button>
        <el-button v-if="activeTab === 'execution'" type="primary" @click="submitForm('draft')">保存草稿</el-button>
        <el-button v-if="activeTab === 'execution'" type="success" @click="submitForm('active')">保存并执行</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup name="EditDrawer" lang="ts">
import { ref, reactive, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import CustomerSelect from './components/customer-select.vue'
import MarketingMethod from './components/marketing-method.vue'
import ExecutionSetting from './components/execution-setting.vue'

// 定义属性
const props = defineProps({
  title: {
    type: String,
    default: ''
  },
  open: {
    type: Boolean,
    default: false
  }
})

// 定义事件
const emit = defineEmits(['update:open', 'submit'])

// 抽屉可见性
const drawerVisible = ref(false)

// 表单引用
const formRef = ref()

// 客户选择组件引用
const customerSelectRef = ref()

// 活动标签页
const activeTab = ref('basic')

// 表单数据
const form = reactive({
  id: null,
  campaignName: '',
  description: '',
  startTime: '',
  endTime: '',
  customerGroup: '{}',
  marketingMethods: '[]',
  triggerType: 'immediate', // immediate: 立即执行, scheduled: 定时执行
  scheduledTime: '', // 定时执行时间
  taskType: 'once', // once: 一次性任务, recurring: 循环任务
  recurringPattern: '' // 循环模式
})

// 表单验证规则
const rules = {
  campaignName: [
    { required: true, message: '活动名称不能为空', trigger: 'blur' }
  ],
  startTime: [
    { required: true, message: '开始时间不能为空', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '结束时间不能为空', trigger: 'change' }
  ]
}

// 判断标签页是否启用
function isTabEnabled(tabName) {
  const tabOrder = ['basic', 'customer', 'method', 'execution']
  const currentIndex = tabOrder.indexOf(tabName)
  const activeIndex = tabOrder.indexOf(activeTab.value)
  
  // 只有当前步骤或之前的步骤是启用的
  // 对于新增操作，需要完成当前步骤的验证才能启用下一步
  return currentIndex <= activeIndex
}

// 处理标签页切换
function handleTabChange(tabName) {
  // 如果标签页未启用，则阻止切换
  if (!isTabEnabled(tabName)) {
    // 重置为当前激活的标签页
    nextTick(() => {
      activeTab.value = activeTab.value
    })
    return false
  }
  
  // 当切换到客户选择标签页时，确保客户树正确显示已选中的客户
  if (tabName === 'customer' && customerSelectRef.value) {
    // 延迟执行，确保DOM已经更新
    setTimeout(() => {
      // 触发客户选择组件更新
      if (typeof customerSelectRef.value.refreshCustomerTree === 'function') {
        customerSelectRef.value.refreshCustomerTree()
      }
    }, 100)
  }
  
  return true
}

// 下一步
function nextStep() {
  // 验证当前步骤的表单
  if (activeTab.value === 'basic') {
    formRef.value.validate((valid) => {
      if (valid) {
        activeTab.value = 'customer'
      } else {
        console.log('基础信息表单验证失败')
        return false
      }
    })
  } else if (activeTab.value === 'customer') {
    // 可以添加客户选择的验证逻辑
    // 检查是否选择了客户
    try {
      const customerGroup = JSON.parse(form.customerGroup)
      // 检查是否选择了客户来源
      const hasSources = customerGroup.sources && customerGroup.sources.length > 0
      // 检查是否选择了具体客户
      const hasSelectedCustomers = customerGroup.selectedCustomers && customerGroup.selectedCustomers.length > 0
      // 检查是否选择了客户标签
      const hasTags = customerGroup.tags && customerGroup.tags.length > 0
      // 检查是否选择了客户分层
      const hasSegments = customerGroup.segments && customerGroup.segments.length > 0
      
      if (!hasSources && !hasSelectedCustomers && !hasTags && !hasSegments) {
        ElMessage.warning('请至少选择一种客户筛选条件：客户来源、指定客户、客户标签或客户分层')
        return false
      }
      
      activeTab.value = 'method'
    } catch (e) {
      ElMessage.error('客户群体数据解析失败')
      return false
    }
  } else if (activeTab.value === 'method') {
    // 添加营销方式的验证逻辑
    try {
      const marketingMethods = JSON.parse(form.marketingMethods)
      if (!marketingMethods || marketingMethods.methods.length === 0) {
        ElMessage.warning('请至少选择一种营销方式')
        return false
      }
      
      // 检查选中的营销方式是否配置完整
      const selectedMethods = marketingMethods.methods
      let hasError = false
      
      // 检查短信配置
      if (selectedMethods.includes('sms')) {
        if (!marketingMethods.sms || !marketingMethods.sms.template) {
          ElMessage.warning('请选择短信模板')
          hasError = true
        }
        if (!marketingMethods.sms || !marketingMethods.sms.content) {
          ElMessage.warning('请输入短信内容')
          hasError = true
        }
      }
      
      // 检查邮件配置
      if (selectedMethods.includes('email')) {
        if (!marketingMethods.email || !marketingMethods.email.template) {
          ElMessage.warning('请选择邮件模板')
          hasError = true
        }
        if (!marketingMethods.email || !marketingMethods.email.subject) {
          ElMessage.warning('请输入邮件主题')
          hasError = true
        }
        if (!marketingMethods.email || !marketingMethods.email.content) {
          ElMessage.warning('请输入邮件内容')
          hasError = true
        }
      }
      
      // 检查微信配置
      if (selectedMethods.includes('wechat')) {
        if (!marketingMethods.wechat || !marketingMethods.wechat.template) {
          ElMessage.warning('请选择微信模板')
          hasError = true
        }
        if (!marketingMethods.wechat || !marketingMethods.wechat.content) {
          ElMessage.warning('请输入微信内容')
          hasError = true
        }
      }
      
      if (hasError) {
        return false
      }
      
      activeTab.value = 'execution'
    } catch (e) {
      ElMessage.error('营销方式数据解析失败')
      return false
    }
  }
}

// 上一步
function prevStep() {
  if (activeTab.value === 'customer') {
    activeTab.value = 'basic'
  } else if (activeTab.value === 'method') {
    activeTab.value = 'customer'
  } else if (activeTab.value === 'execution') {
    activeTab.value = 'method'
  }
}

// 监听open变化
watch(() => props.open, (val) => {
  drawerVisible.value = val
  // 重置到第一步
  if (val) {
    activeTab.value = 'basic'
  }
})

// 设置表单数据
function setForm(data) {
  // 重置表单
  Object.keys(form).forEach(key => {
    if (key !== 'customerGroup' && key !== 'marketingMethods' && key !== 'triggerType' && key !== 'taskType') {
      form[key] = ''
    }
  })
  form.customerGroup = '{}'
  form.marketingMethods = '[]'
  form.triggerType = 'immediate'
  form.taskType = 'once'
  
  // 填充数据
  Object.keys(form).forEach(key => {
    if (data[key] !== undefined && data[key] !== null) {
      // 特殊处理日期字段
      if (['startTime', 'endTime', 'scheduledTime'].includes(key)) {
        if (data[key]) {
          // 如果是字符串格式的日期，转换为Date对象
          if (typeof data[key] === 'string') {
            form[key] = new Date(data[key].replace(/-/g, '/').replace('T', ' ').replace(/\.\d+Z?/, ''))
          } else {
            form[key] = data[key]
          }
        }
      } 
      // 特殊处理JSON字符串字段
      else if (key === 'customerGroup' || key === 'marketingMethods') {
        if (typeof data[key] === 'string') {
          try {
            form[key] = data[key]
          } catch (e) {
            console.error('解析JSON字符串失败:', e)
            form[key] = key === 'customerGroup' ? '{}' : '[]'
          }
        } else {
          form[key] = JSON.stringify(data[key])
        }
      } 
      // 其他字段直接赋值
      else {
        form[key] = data[key]
      }
    }
  })
  
  // 确保在设置完数据后，刷新客户选择组件
  nextTick(() => {
    if (customerSelectRef.value && typeof customerSelectRef.value.refreshCustomerTree === 'function') {
      customerSelectRef.value.refreshCustomerTree()
    }
  })
}

// 提交表单
function submitForm(status) {
  formRef.value.validate((valid) => {
    if (valid) {
      // 设置状态
      form.status = status
      
      // 构造提交数据
      const submitData = { ...form }
      
      // 格式化日期字段为 yyyy-MM-dd HH:mm:ss 格式
      const formatDate = (date) => {
        if (!date) return null
        if (typeof date === 'string') return date
        const d = new Date(date)
        const year = d.getFullYear()
        const month = String(d.getMonth() + 1).padStart(2, '0')
        const day = String(d.getDate()).padStart(2, '0')
        const hours = String(d.getHours()).padStart(2, '0')
        const minutes = String(d.getMinutes()).padStart(2, '0')
        const seconds = String(d.getSeconds()).padStart(2, '0')
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
      }
      
      submitData.startTime = formatDate(submitData.startTime)
      submitData.endTime = formatDate(submitData.endTime)
      submitData.scheduledTime = formatDate(submitData.scheduledTime)
      
      // 确保客户群体和营销方式是字符串格式
      if (typeof form.customerGroup !== 'string') {
        submitData.customerGroup = JSON.stringify(form.customerGroup)
      } else {
        // 确保获取最新的selectedCustomers数据
        try {
          const customerGroup = JSON.parse(form.customerGroup);
          // 从customer-select组件获取最新的选中客户
          if (customerSelectRef.value) {
            customerGroup.selectedCustomers = customerSelectRef.value.getSelectedCustomers() || [];
          }
          submitData.customerGroup = JSON.stringify(customerGroup);
        } catch (e) {
          console.error('处理客户群体数据时出错:', e);
          submitData.customerGroup = form.customerGroup;
        }
      }
      
      if (typeof form.marketingMethods !== 'string') {
        submitData.marketingMethods = JSON.stringify(form.marketingMethods)
      } else {
        submitData.marketingMethods = form.marketingMethods
      }
      
      // 发送提交事件
      emit('submit', submitData)
    } else {
      console.log('表单验证失败')
      return false
    }
  })
}

// 关闭处理
function handleClose() {
  drawerVisible.value = false
  emit('update:open', false)
  // 重置表单
  formRef.value.resetFields()
  Object.keys(form).forEach(key => {
    if (key !== 'customerGroup' && key !== 'marketingMethods' && key !== 'triggerType' && key !== 'taskType') {
      form[key] = ''
    }
  })
  form.customerGroup = '{}'
  form.marketingMethods = '[]'
  form.triggerType = 'immediate'
  form.taskType = 'once'
  // 重置到第一步
  activeTab.value = 'basic'
}

// 暴露方法
defineExpose({
  setForm
})
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}
</style>